package com.ias.agdis_r.manager;

import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;

import com.ias.agdis_r.R;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.preference.VoiceEffectPreference;
import com.ias.agdis_r.util.ShowToast;
//import com.iflytek.speech.SpeechUtility;

import java.util.HashSet;
import java.util.Set;

/**
 * 效果管理
 * 
 * @author wanghu
 * 
 */
public class EffectManager {

	private static EffectManager instance;

	private SoundPool soundPool;			// 读取音效
	private SparseIntArray mySoundPoolMap;	// 音效池
	private AudioManager mAudioManager;		// 控制声音大小
	private float volume;					// 左右声道音量大小
	private Vibrator myVibrator;			// 震动控制

	private TTSManager tts;					// 语音合成器
	private boolean isTTSPause = false;

	/** 音效及震动配置 SharedPreferences */
	private SharedPreferences mRingtonePreferences;

	/** SharedPreferences对应偏好的key */
	private SparseArray<String> mRingtonePrefsKeyMap = new SparseArray<>();		// 收到消息提示音 / 收到任务提示音
	private SparseArray<String> mVibratePrefsKeyMap = new SparseArray<>();		// 收到消息震动提示 / 收到任务震动提示

	/** 已经被替换的声音特效集合 */
	private Set<Integer> soundReplaced = new HashSet<Integer>();
	private Ringtone ringtone1, ringtone2;				// 收到消息 / 任务 音效

	public static int RECEIVE_PRODUCT_TYPE = 0;
	public static int RECEIVE_INFO_TYPE = 0;
	public static int NET_UNAVAILABLE_TYPE = 0;
	public static int DOC_UPDATE_TYPE = 0;
	public static int TTS_OPEN = 0;
	public static int TTS_OPEN_TYPE = 0;
	public static int TTS_OPEN_TOAST = 0;

	// TTS_OPEN_TYPE 1基础&网络信息（不弹出吐司），2任务信息，4工作短语&航班查询，8任务变更&订阅，16情况反映&提示信息，32对讲
	public static final int TTS_TYPE_NONE = 0;
	public static final int TTS_TYPE_BASE = 1;
	public static final int TTS_TYPE_TASK = 2;
	public static final int TTS_TYPE_WORKMSG = 4;
	public static final int TTS_TYPE_TASKCHANGE = 8;
	public static final int TTS_TYPE_UPTO = 16;
	public static final int TTS_TYPE_PTT = 32;
	public static final int TTS_TYPE_TEMP = 64; // 临时用的，在正式版本中不配置

	private EffectManager() {
		Context context = DataBaseManager.getInstance().getContext();
		mRingtonePreferences = context.getApplicationContext().getSharedPreferences(ParameterModel.T_VIBERATION_EFFECT, Context.MODE_PRIVATE);
		myVibrator = (Vibrator) context.getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
	}

	public static EffectManager getInstance() {
		if (instance == null) {
			instance = new EffectManager();
		}
		return instance;
	}

	public void initVoice() {
		loadEffectType();	// 加载音效配置
		initTTS();			// 初始化语音合成系统
		Context context = DataBaseManager.getInstance().getContext();

		// 收到生产通告声效
		mRingtonePrefsKeyMap.put(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO, context.getString(R.string.ring_receive_info));	// 收到消息时 提示音
		mVibratePrefsKeyMap.put(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO, context.getString(R.string.shake_receive_info));  // 收到消息时 震动提示
		soundReplaced.add(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO);
		// 收到任务声效
		mRingtonePrefsKeyMap.put(ParameterModel.MUSIC_EFFECT_RECEIVE_TASK, context.getString(R.string.ring_receive_product)); // 收到任务时 提示音
		mVibratePrefsKeyMap.put(ParameterModel.MUSIC_EFFECT_RECEIVE_TASK, context.getString(R.string.shake_receive_product)); // 收到任务时 震动提示
		soundReplaced.add(ParameterModel.MUSIC_EFFECT_RECEIVE_TASK);

		String defValue = "content://settings/system/notification_sound";
		String uri1 = mRingtonePreferences.getString(mRingtonePrefsKeyMap.get(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO), defValue);
		ringtone1 = RingtoneManager.getRingtone(context, Uri.parse(uri1));
		ringtone1.setStreamType(AudioManager.STREAM_MUSIC);
		String uri2 = mRingtonePreferences.getString(mRingtonePrefsKeyMap.get(ParameterModel.MUSIC_EFFECT_RECEIVE_TASK), defValue);
		ringtone2 = RingtoneManager.getRingtone(context, Uri.parse(uri2));
		ringtone2.setStreamType(AudioManager.STREAM_MUSIC);

		// 左右声道音量大小
		AudioManager mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		if (mgr != null) {
			float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
			float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
			volume = streamVolumeCurrent / streamVolumeMax;
		}

		// 初始化活动音效（短声音）
		soundPool = new SoundPool(11, AudioManager.STREAM_MUSIC, 5);
		mySoundPoolMap = new SparseIntArray();
		// 收到生产通告声效 1
		mySoundPoolMap.put(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO, soundPool.load(context, R.raw.infosound, 1));
		// 收到任务声效 2
		mySoundPoolMap.put(ParameterModel.MUSIC_EFFECT_RECEIVE_TASK, soundPool.load(context, R.raw.tasksound, 1));
		// 对讲不在线提示 3
		mySoundPoolMap.put(ParameterModel.MUSIC_EFFECT_PTT_OFFLINE, soundPool.load(context, R.raw.error, 1));
		// 未登录提示 4
		mySoundPoolMap.put(ParameterModel.MUSIC_EFFECT_UNLOGIN_REMIND, soundPool.load(context, R.raw.remind, 1));
		// SD卡不可用 5
		mySoundPoolMap.put(ParameterModel.MUSIC_EFFECT_SDCARD_UNABLE, soundPool.load(context, R.raw.sdunable, 1));
		// AGDIS被服务器注销 6
		mySoundPoolMap.put(ParameterModel.MUSIC_EFFECT_USER_OFFLINE, soundPool.load(context, R.raw.offline, 1));
		// 网络不可用 7
		mySoundPoolMap.put(ParameterModel.MUSIC_EFFECT_NET_UNAVAILABLE, soundPool.load(context, R.raw.net_unavailable, 1));
		// 单据更新 8
		mySoundPoolMap.put(ParameterModel.MUSIC_EFFECT_DOC_UPDATE, soundPool.load(context, R.raw.doc_update, 1));
	}

	/** 加载音效配置 */
	private void loadEffectType() {
		// 收到生产通告时(0：震动 1：声音,2：震动+声音)
		EffectManager.RECEIVE_PRODUCT_TYPE = DataBaseManager.getInstance().getInt(ParameterModel.T_VIBERATION_EFFECT, ParameterModel.RECEIVE_PRODUCT);
		// 收到消息时(0：震动 1：声音 2：震动+声音)
		EffectManager.RECEIVE_INFO_TYPE = DataBaseManager.getInstance().getInt(ParameterModel.T_VIBERATION_EFFECT, ParameterModel.RECEIVE_INFO);
		// 网络不可用时(0：不播放声音 1:播放声音)
		EffectManager.NET_UNAVAILABLE_TYPE = DataBaseManager.getInstance().getInt(ParameterModel.T_VIBERATION_EFFECT, ParameterModel.NET_UNAVAILABLE);
		// 单据更新提示音(0：震动 1：声音,2：震动+声音)
		EffectManager.DOC_UPDATE_TYPE = DataBaseManager.getInstance().getInt(ParameterModel.T_VIBERATION_EFFECT, ParameterModel.DOC_UPDATE);
		// 语音播报 （0：禁用播报 1：启用播报）
		EffectManager.TTS_OPEN = DataBaseManager.getInstance().getInt(ParameterModel.T_VIBERATION_EFFECT, ParameterModel.T_VOICE_EFFECT);
	}

	/** 初始化语音合成系统 */
	public void initTTS() {
		Context context = DataBaseManager.getInstance().getContext();

		String prefs = mRingtonePreferences.getString(context.getString(R.string.settings_voice_effect), VoiceEffectPreference.DEFAULT_FREFS);
		boolean ttsOpen = VoiceEffectPreference.isTTSOpen(prefs);
		EffectManager.TTS_OPEN = ttsOpen ? 1 : 0;
		System.out.println("语音播报开关：" + ttsOpen);

		if (EffectManager.TTS_OPEN == 1) {
			EffectManager.TTS_OPEN_TYPE = VoiceEffectPreference.getTTSOpenType(prefs);
			System.out.println("语音播报类型：" + EffectManager.TTS_OPEN_TYPE);

			// 判断是否安装讯飞输入法
			//String[] speechStrings = SpeechUtility.getUtility(context).queryAvailableEngines();
			//if (speechStrings == null || speechStrings.length <= 0)
			//	return;

			if (EffectManager.TTS_OPEN_TYPE == 0) {
				EffectManager.TTS_OPEN = 0;
			} else {
				EffectManager.TTS_OPEN_TOAST = DataBaseManager.getInstance().getInt(ParameterModel.T_VIBERATION_EFFECT, ParameterModel.T_VOICE_EFFECT_TOAST);
				tts = TTSManager.getInstance();
				tts.initTTS(context);
			}
		}
	}

	/**
	 * 播放短音效
	 * @param key 音效池中Key
	 */
	public void playSound(int key) {
		if (soundPool == null) {
			initVoice();
		}

		if (soundReplaced.contains(key)) {
			// 如果设置震动
			if (mRingtonePreferences.getBoolean(mVibratePrefsKeyMap.get(key), false)) {
				System.out.println("震动...");
				vibrate();
			}
			// 音效
//			if (mRingtonePrefsKeyMap.get(key).equals(ParameterModel.MUSIC_EFFECT_RECEIVE_INFO)) {
			if (key == ParameterModel.MUSIC_EFFECT_RECEIVE_INFO && ringtone1 != null) {
				System.out.println("收到生产通告声效...");
				ringtone1.play();
			} else if (key == ParameterModel.MUSIC_EFFECT_RECEIVE_TASK && ringtone2 != null) {
				System.out.println("收到任务声效...");
				ringtone2.play();
			}
			return;
		}
		soundPool.play(mySoundPoolMap.get(key), volume, volume, 1, 0, 1f);
	}

	/**
	 * 语音播报
	 * @param type 类型
	 * @param txt 语音内容
	 * @param hanFln 是否有航班号，如果有航班号，则将内容增加空格，保证航班号按照字母读出。
	 */
	public void ttsPlay(int type, String txt, boolean hanFln) {
		if (TextUtils.isEmpty(txt))
			return;
		if (tts == null || TTS_OPEN != 1) {
			//EffectManager.TTS_TYPE_BASE != type &&
			if (EffectManager.TTS_TYPE_TEMP != type) {
				ShowToast.get().show(txt);
			}
			return;
		}

		if (0 != (EffectManager.TTS_OPEN_TYPE & type)) {
			//&& EffectManager.TTS_TYPE_BASE != type
			if (0 != EffectManager.TTS_OPEN_TOAST) {
				if (EffectManager.TTS_TYPE_TEMP != type) {
					Context context = DataBaseManager.getInstance().getContext();
					ShowToast.get().show(context.getString(R.string.EM_1) + txt + context.getString(R.string.EM_2));
				}
			}

			if (isTTSPause)	// 如果TTS是暂停状态，不播放新语音
				return;

			tts.ttsPlay(hanFln ? appendSpace(txt) : txt);
		} else if (EffectManager.TTS_TYPE_TEMP != type) {
			ShowToast.get().show(txt);
		}
	}

	private String appendSpace(String para) {
		int length = para.length();
		char[] value = new char[length << 1];
		for (int i = 0, j = 0; i < length; ++i, j = i << 1) {
			value[j] = para.charAt(i);
			value[1 + j] = ' ';
		}
		return new String(value);
	}

	public void ttsPause() {
		isTTSPause = true;
		if (TTS_OPEN == 1 && null != tts) {
			if (0 != EffectManager.TTS_OPEN_TOAST) {
				Context context = DataBaseManager.getInstance().getContext();
				ShowToast.get().show(context.getString(R.string.EM_3));
			}
			tts.ttsPause();
		}
	}

	public void ttsResume() {
		isTTSPause = false;
		if (TTS_OPEN == 1 && null != tts) {
			tts.ttsResume();
		}
	}

	public void ttsCancel() {
		if (TTS_OPEN == 1 && null != tts) {
			if (0 != EffectManager.TTS_OPEN_TOAST) {
				Context context = DataBaseManager.getInstance().getContext();
				ShowToast.get().show(context.getString(R.string.EM_4));
			}
			tts.ttsCancel();
		}
	}

	public void onDestory() {
		if (tts != null) {
			tts.onDestory();
		}
	}


	//=======================================================================================================================

	/** 震动 */
	public void vibrate() {
		if (myVibrator != null) {
			long[] pattern = { 600, 180, 400, 80, 600, 120, 400, 80 };
			myVibrator.vibrate(pattern, -1);
		}
	}

	/** 调高音量 */
	public void setMusicVolumeRaise(){
		if (mAudioManager == null) {
			Context context = DataBaseManager.getInstance().getContext();
			this.mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		}
		if (mAudioManager != null) {
			mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
		}
	}

	/** 调低音量 */
	public void setMusicVolumeLower(){
		if (mAudioManager == null) {
			Context context = DataBaseManager.getInstance().getContext();
			this.mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		}
		if (mAudioManager != null) {
			mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
		}
	}
}
